package com.bluewave.goaltracker;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.ActivityInfo;
import android.database.Cursor;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.CheckBox;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import com.bluewave.goaltracker.utils.ApplicationDBAdapter;
import com.bluewave.goaltracker.utils.CalendarView;
import com.bluewave.goaltracker.utils.CalendarView.OnCellTouchListener;
import com.bluewave.goaltracker.utils.Cell;
import com.bluewave.goaltracker.utils.Goal;

public class GoalListActivity extends Activity implements OnClickListener {

	private Context m_context;
	private CalendarView m_calendarView;
	private ArrayList<Date> m_dateList;
	private long m_goalId = -1;
	private int m_trackPeriod, m_trackDay;
	private TextView m_type_goal;
	private TextView m_weekPercent;
	private TextView m_mothPercent;
	private ImageButton m_next;
	private ImageButton m_previous;
	private int screenType = Goal.MONTHLY;
	private ApplicationDBAdapter m_db;
	private Cursor m_goalCursor;
	private float m_xFinger = 0;
	public CheckBox m_cb;
	private ListView m_goalList ;
	private Date m_calDate; 
	private TextView m_mothView = null;
	private TextView m_yearView = null;
	String[] m_months = { "January", "February", "March", "April", "May", "June",
			"July", "August", "September", "October", "November", "December" };
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		m_calDate = new Date();
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
		setContentView(R.layout.goal_list);
		m_context = this;
		m_mothView = (TextView) findViewById(R.id.t_month);
		m_yearView = (TextView) findViewById(R.id.t_year);
		loadColor();
		m_weekPercent = (TextView) findViewById(R.id.t_Weekheader);
		m_mothPercent = (TextView) findViewById(R.id.t_Monthheader);
		loadQuotes();
		loadQuarterlyAlerts();
		
		m_type_goal = (TextView) findViewById(R.id.type_goal);

		m_next = (ImageButton) findViewById(R.id.b_next);
		m_next.setOnClickListener(this);

		m_previous = (ImageButton) findViewById(R.id.b_previous);
		m_previous.setOnClickListener(this);

		screenType = Goal.MONTHLY;
		
		m_goalList = (ListView) findViewById(R.id.goalList);
		
		loadList();
		m_goalCursor.moveToFirst();
		if(m_goalCursor.getCount() > 0){
			m_goalId = m_goalCursor.getLong(m_goalCursor
					.getColumnIndex(ApplicationDBAdapter.GOAL_KEY_ID));
		}

		m_trackPeriod=Goal.TrackPeriod.DAILY;
		m_trackDay=0;

		m_calendarView = (CalendarView) findViewById(R.id.calendar);
		m_calendarView.setTrackValues(m_trackPeriod, m_trackDay);

		m_calendarView.setOnCellTouchListener(new OnCellTouchListener() {

			@Override
			public void onTouchCell(MotionEvent event, Cell cell) {
				if(screenType != Goal.MONTHLY){
					return;
				}
				if (!(cell.getType() == Cell.GREY_CELL)) {

					int day = cell.getDayOfMonth();

					if (day <= new Date().getDate()) {
						Calendar calendar = Calendar.getInstance();

						calendar.set(calendar.get(Calendar.YEAR),
								calendar.get(Calendar.MONTH), day);

						Date date = calendar.getTime();

						String format = "dd-MM-yyyy";

						SimpleDateFormat sdf = new SimpleDateFormat(format);

						String dateString = sdf.format(date);

						ApplicationDBAdapter db = new ApplicationDBAdapter(m_context);

						db.open();

						db.toggleGoalUpdateStatus(m_goalId, dateString);

						db.close();

						refreshCalendar();
					}

				}	
				
			}

			@Override
			public void onTouchWeek(MotionEvent event) {
				if(screenType != Goal.MONTHLY){
					return;
				}
				float m_currentFinger = event.getX();
				switch (event.getAction())
		        {
					
		            case MotionEvent.ACTION_DOWN:
		            {       
		            	m_xFinger = event.getX();
		                break; 
		            }
		            case MotionEvent.ACTION_UP:
		            {                      	
		            	m_xFinger = 0; 
		                 break;
		            }
		            case MotionEvent.ACTION_MOVE:
		            {         	
		            	System.out.print("Move");
		    			if((m_currentFinger - m_xFinger) > 100){
		//  go to next  		
		    				m_calDate.setMonth(m_calDate.getMonth()-1);
		    				m_xFinger = m_currentFinger;
		    				refreshCalendar();
		    			}else if((m_xFinger - m_currentFinger) > 100){
		    				m_calDate.setMonth(m_calDate.getMonth()+1);
		    				m_xFinger = m_currentFinger;
		    				refreshCalendar();
		    			}
		                break;
		            }
		        }
			}
		});

		refreshCalendar();
	}
	
	private void loadList() {
		m_type_goal
				.setText(getResources().getStringArray(R.array.goal_types)[screenType]);

		String[] displayFields = new String[] { ApplicationDBAdapter.GOAL_NAME };
		int[] displayViews = new int[] { R.id.goal_name };

		m_db = new ApplicationDBAdapter(m_context);

		m_db.open();

		m_goalCursor = m_db.getGoalsCursor(screenType);

		SimpleCursorAdapter goalListCursorAdapter;

		if (screenType == Goal.MONTHLY) {
			goalListCursorAdapter = new GoalListCursorAdapter(m_context,
					R.layout.goal_row, m_goalCursor, displayFields, displayViews);
		} else if (screenType == Goal.YEARLY) {
			goalListCursorAdapter = new GoalListYearlyCursorAdapter(m_context,
					R.layout.goal_row_yearly, m_goalCursor, displayFields,
					displayViews);
		} else {
			goalListCursorAdapter = new GoalListCursorAdapter(m_context,
					R.layout.goal_row_none, m_goalCursor, displayFields,
					displayViews);
		}
		m_goalList.setAdapter(goalListCursorAdapter);
	}
	
	public void refreshCalendar() {
		
		if(m_goalId == -1 || screenType != Goal.MONTHLY){
			return;
		}
		m_calendarView.loadCalendar(m_calDate);

		ApplicationDBAdapter db = new ApplicationDBAdapter(m_context);

		db.open();
		
		m_dateList = db.getMarkedDateList2(m_goalId, m_calDate,m_trackPeriod);
		
		m_calendarView.markDate(m_dateList);
		float nProgressPercent = db.getProgressPercent(m_goalId, m_calDate);
		m_weekPercent.setText("W "+nProgressPercent+"%");
		float previousMonthsProgressPercent = db.getPreviousMonthsProgressPercent(m_goalId, m_calDate);
		m_mothPercent.setText(("M "+previousMonthsProgressPercent+"%"));
		db.close();
		m_mothView.setText(m_months[m_calDate.getMonth()]);
		String year = android.text.format.DateFormat.format("yyyy", m_calDate).toString();
		m_yearView.setText(year+"");
		m_calendarView.invalidate();

	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle item selection
		// Handle item selection
		switch (item.getItemId()) {
		case R.id.preferences:
			startActivity(new Intent(this, MyPreferenceActivity.class));
			return true;
		case R.id.share:
			Intent intent = new Intent(Intent.ACTION_SEND);
			intent.setType("text/plain");

			intent.putExtra(Intent.EXTRA_SUBJECT, getApplicationInfo().name);
			intent.putExtra(
					Intent.EXTRA_TEXT,
					"Check out this wonderful app that helps me organize and track my personal goals, get it here �\n http://market.android.com/details?id=com.bluewave.goaltracker");

			Intent chooser = Intent.createChooser(intent,
					"Share 'Goal Coach' App");
			startActivity(chooser);
			return true;
		case R.id.howtouseOptionMenu:
			startActivity(new Intent(this, HowToUseActivity.class));
			return true;
			
		case R.id.rewardOptionMenu:
			startActivity(new Intent(this,RewardsActivity.class));
			return true;
		case R.id.addGoalOptionMenu:
			startActivityForResult(
					new Intent(m_context, AddGoalActivity.class).putExtra(
							"screen_type", screenType), 0);
			return true;	
		
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	public void onStart() {
		super.onStart();
	}

	public void onStop() {
		super.onStop();
	}


	@Override
	protected void onResume() {
		super.onResume();
		m_goalCursor.requery();
		loadColor();
	}
	
	public class GoalListCursorAdapter extends SimpleCursorAdapter {

		private Cursor cursor;
		private Context context;
		private int layout;

		public GoalListCursorAdapter(Context context, int layout, Cursor c,
				String[] from, int[] to) {
			super(context, layout, c, from, to);
			this.cursor = c;
			this.context = context;
			this.layout = layout;

		}

		public View getView(int pos, View inView, ViewGroup parent) {
			View view = inView;
			if (view == null) {
				LayoutInflater inflater = (LayoutInflater) context
						.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				view = inflater.inflate(layout, null);
			}

			this.cursor.moveToPosition(pos);

			final long goalId = this.cursor.getLong(this.cursor
					.getColumnIndex(ApplicationDBAdapter.GOAL_KEY_ID));

			String goalName = this.cursor.getString(this.cursor
					.getColumnIndex(ApplicationDBAdapter.GOAL_NAME));

			TextView t_goalName = (TextView) view.findViewById(R.id.goal_name);

			t_goalName.setText(goalName);

			if (screenType == Goal.MONTHLY) {
				
				view.setOnClickListener(new OnClickListener() {
					
					@Override
					public void onClick(View view) {
						m_goalId = goalId;
						refreshCalendar();
					}
				});

			}
			view.setOnLongClickListener(new OnLongClickListener() {
				
				@Override
				public boolean onLongClick(View view) {
					Intent intent = new Intent(m_context, AddGoalActivity.class);
					intent.putExtra("Edit", 100);
					intent.putExtra("id", goalId);
					startActivityForResult(intent, 0);
					return true;
				}
			});
			
			return (view);
		}
	}

	@Override
	public void finish() {
		super.finish();
		m_goalCursor.close();
		m_db.close();
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		if (resultCode == RESULT_OK) {

			screenType = data.getIntExtra("screen_type", Goal.MONTHLY);

			loadList();
		}
	}
	
	public void onClick(View view) {
		if (view.getId() == m_next.getId()) {

			if (screenType == 0) {

				screenType = 1;

				loadList();

			} else if (screenType == 1) {

				screenType = 2;

				loadList();

			} else {

				screenType = 0;

				loadList();

			}

		} else if (view.getId() == m_previous.getId()) {
			if (screenType == 0) {

				screenType = 2;

				loadList();

			} else if (screenType == 1) {

				screenType = 0;

				loadList();

			} else {

				screenType = 1;

				loadList();

			}

		}
	}
	private void loadColor(){
		SharedPreferences pres = PreferenceManager
		.getDefaultSharedPreferences(m_context);
		int backgroundColor = pres.getInt("background_color", 0);
		LinearLayout backBroundLayout = (LinearLayout) findViewById(R.id.goal_list);
		backBroundLayout.setBackgroundColor(backgroundColor);
	
	}
	public void loadQuarterlyAlerts() {

		Context mContext = getApplicationContext();

		SharedPreferences pref = PreferenceManager
				.getDefaultSharedPreferences(mContext);

		long quarterly_alert = pref.getLong("quarterly_alert", 0);

		if (quarterly_alert == 0) {
			SharedPreferences.Editor editor = pref.edit();
			editor.putLong("quarterly_alert", new Date().getTime());

			Intent intent = new Intent("com.bluewave.AlarmBroadcastReceiver");
			intent.putExtra("alert_type", Goal.QUARTERLY);

			sendBroadcast(intent);
		}

	}

	public void loadQuotes() {

		String[] quotes = getResources().getStringArray(R.array.quotes);

		Context mContext = getApplicationContext();

		SharedPreferences pref = PreferenceManager
				.getDefaultSharedPreferences(mContext);

		int quote_no = pref.getInt("quote_no", 123);
		Editor edit=pref.edit();
		edit.putLong("last_used", System.currentTimeMillis());
		edit.commit();

		if (quote_no == 123) {
			SharedPreferences.Editor editor = pref.edit();
			editor.putInt("quote_no", 0);
			editor.commit();
			quote_no = 0;

		}

		TextView t_quote = (TextView) findViewById(R.id.t_quotes);
		t_quote.setText(quotes[quote_no]);

		if (quote_no < quotes.length - 1) {
			SharedPreferences.Editor editor = pref.edit();
			quote_no = quote_no + 1;
			editor.putInt("quote_no", quote_no);
			editor.commit();
		} else {
			SharedPreferences.Editor editor = pref.edit();
			editor.putInt("quote_no", 0);
			editor.commit();
		}

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.menu_in_list, menu);
		return true;
	}
	
	public class GoalListYearlyCursorAdapter extends SimpleCursorAdapter {

		private Cursor cursor;
		private Context context;
		private int layout;

		public GoalListYearlyCursorAdapter(Context context, int layout,
				Cursor c, String[] from, int[] to) {
			super(context, layout, c, from, to);
			this.cursor = c;
			this.context = context;
			this.layout = layout;

		}

		public View getView(int pos, View inView, ViewGroup parent) {
			View view = inView;
			if (view == null) {
				LayoutInflater inflater = (LayoutInflater) context
						.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				view = inflater.inflate(layout, null);
			}

			this.cursor.moveToPosition(pos);

			String goalName = this.cursor.getString(this.cursor
					.getColumnIndex(ApplicationDBAdapter.GOAL_NAME));

			String goalDate = this.cursor.getString(this.cursor
					.getColumnIndex(ApplicationDBAdapter.GOAL_CREATED_DATE));

			TextView t_goalName = (TextView) view.findViewById(R.id.goal_name);

			t_goalName.setText(goalName);

			TextView t_goaldate = (TextView) view.findViewById(R.id.goal_date);

			DateFormat formatter, formatter2;
			Date date = null;
			formatter = new SimpleDateFormat("dd-MMMM-yyyy");
			formatter2 = new SimpleDateFormat("dd-MM-yyyy");

			try {
				date = (Date) formatter2.parse(goalDate);
			} catch (ParseException e) {
			e.printStackTrace();
			}
			String s = formatter.format(date);

			t_goaldate.setText(s);
			
			view.setOnLongClickListener(new OnLongClickListener() {
				
				@Override
				public boolean onLongClick(View arg0) {
					Intent intent = new Intent(m_context, AddGoalActivity.class);
					intent.putExtra("Edit", 100);
					intent.putExtra("id", m_goalId);
					startActivityForResult(intent, 0);
					return true;
				}
			});

			return (view);
		}
	}

}
